import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QTableWidgetItem, QPushButton, QVBoxLayout, QWidget, QDialog, QLabel, QLineEdit, QCheckBox, QFormLayout, QHeaderView,QTableWidget
from PySide6.QtCore import Qt
import pymysql

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("学生信息管理系统")
        self.setGeometry(100, 100, 800, 600)

        self.table = QTableWidget()
        self.load_data()

        self.delete_button = QPushButton("删除")
        self.delete_button.clicked.connect(self.delete_students)

        self.add_button = QPushButton("添加")
        self.add_button.clicked.connect(self.add_student)

        layout = QVBoxLayout()
        layout.addWidget(self.table)
        layout.addWidget(self.delete_button)
        layout.addWidget(self.add_button)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

    def load_data(self):
        # 连接数据库并获取学生信息
        connection = pymysql.connect(host='localhost', user='root', password='123456', database='qt')
        cursor = connection.cursor()
        cursor.execute("SELECT * FROM students")
        data = cursor.fetchall()
        cursor.close()
        connection.close()

        # 设置表格属性
        self.table.setColumnCount(7)
        self.table.setHorizontalHeaderLabels(['id', '姓名', '年龄', '手机号', '学制', '学籍', '操作'])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        # 填充表格数据
        self.table.setRowCount(len(data))
        for i, row in enumerate(data):
            for j, value in enumerate(row):
                if j == 0:
                    checkbox = QCheckBox()
                    self.table.setCellWidget(i, j, checkbox)
                else:
                    item = QTableWidgetItem(str(value))
                    item.setFlags(item.flags() & ~Qt.ItemIsEditable)
                    self.table.setItem(i, j, item)
            detail_button = QPushButton("详情")
            detail_button.clicked.connect(lambda _, row=row: self.show_details(row))
            self.table.setCellWidget(i, 6, detail_button)



    def show_details(self, student):
        dialog = QDialog(self)
        dialog.setWindowTitle("学生详情")
        dialog.setGeometry(300, 300, 400, 200)

        layout = QVBoxLayout()
        for key, value in zip(['id','姓名', '年龄', '手机号', '学制', '学籍'], student):
            label = QLabel(f"{key}: {value}")
            layout.addWidget(label)

        dialog.setLayout(layout)
        dialog.exec()

    def delete_students(self):
        self.selected_rows = []
        for i in range(self.table.rowCount()):
            checkbox = self.table.cellWidget(i, 6)
            if checkbox and checkbox.isChecked():
                self.selected_rows.append(i)
        print(self.selected_rows)
        connection = pymysql.connect(host='localhost', user='root', password='123456', database='qt')
        cursor = connection.cursor()
        for row in self.selected_rows:
            student_id = self.table.item(row, 0).text()
            cursor.execute("DELETE FROM students WHERE id=%s", (student_id,))
        connection.commit()

        cursor.close()
        connection.close()

        self.load_data()

    def add_student(self):
        dialog = QDialog(self)
        dialog.setWindowTitle("添加学生")
        dialog.setGeometry(300, 300, 400, 200)

        layout = QVBoxLayout()
        form_layout = QFormLayout()
        form_layout.addRow("姓名", QLineEdit())
        form_layout.addRow("手机号", QLineEdit())
        form_layout.addRow("年龄", QLineEdit())
        form_layout.addRow("学制", QLineEdit())
        form_layout.addRow("学籍", QLineEdit())
        layout.addLayout(form_layout)

        submit_button = QPushButton("提交")
        submit_button.clicked.connect(lambda: self.submit_student(form_layout, dialog))
        layout.addWidget(submit_button)

        dialog.setLayout(layout)
        dialog.exec()

    def submit_student(self, form_layout, dialog):
        data = [field.text() for field in form_layout]
        connection = pymysql.connect(host='localhost', user='root', password='123456', database='qt')
        cursor = connection.cursor()
        cursor.execute("INSERT INTO students (name,age ,phone,education, status) VALUES (%s, %s, %s, %s, %s)", data)
        connection.commit()
        cursor.close()
        connection.close()
        dialog.accept()
        self.load_data()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
